package com.bms.tools;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;

import javax.imageio.ImageIO;

import net.sf.json.JSONObject;

public class PictureTool {
	
	
	/**
	 * 切图
	 * @param sourceFile
	 * @param targetPath
	 * @param posesJson
	 * @param prefix
	 * @return
	 * @throws IOException
	 */
	public static File cutPic(File sourceFile,String targetPath,JSONObject posesJson,String prefix) throws IOException{
		
//		String prefix = getExName(sourceFile);	//扩展名
		
		Integer x = (new BigDecimal((String)posesJson.get("x")).setScale(0, BigDecimal.ROUND_HALF_UP)).intValue();//四舍五入取整  
		Integer y = (new BigDecimal((String)posesJson.get("y")).setScale(0, BigDecimal.ROUND_HALF_UP)).intValue();//四舍五入取整  
		Integer w = (new BigDecimal((String)posesJson.get("w")).setScale(0, BigDecimal.ROUND_HALF_UP)).intValue();//四舍五入取整  
		Integer h = (new BigDecimal((String)posesJson.get("h")).setScale(0, BigDecimal.ROUND_HALF_UP)).intValue();//四舍五入取整  
		
		File outFile = new File(targetPath);
		
		BufferedImage bufferedImage = ImageIO.read(sourceFile);
		
		//切图										(x:图片左上角x坐标；y：图片左上角y坐标；w：宽度；h:高度)
		BufferedImage bf = bufferedImage.getSubimage(x, y, w, h);
		boolean bl = ImageIO.write(bf, prefix, outFile);
		if(bl){
			return outFile;
		}
		return null;
	}
	
	public static File ThumbnailPic(File sourceFile,String targetPath,double thumbFactor,String prefix) throws IOException{
		
		File outFile = new File(targetPath);
		
		BufferedImage bufferedImage = ImageIO.read(sourceFile);
		
		//缩略图
		double bl = thumbFactor;
		
		int width = bufferedImage.getWidth();
		int height = bufferedImage.getHeight();
		
		int destWidth = new BigDecimal(width).multiply(new BigDecimal(bl)).intValue();
		int destHeight = new BigDecimal(height).multiply(new BigDecimal(bl)).intValue();
		
		
		BufferedImage tag = new BufferedImage(destWidth, destHeight,BufferedImage.TYPE_3BYTE_BGR);
		tag.getGraphics().drawImage(bufferedImage, 0, 0, destWidth, destHeight, null); //绘制缩小后的图
		boolean bls = ImageIO.write(tag, prefix , outFile);
		if(bls){
			return outFile;
		}
		return null;
	}
	
	private static String getExName(File f){
		String fileName=f.getName();      
		String prefix=fileName.substring(fileName.lastIndexOf(".")+1);      
		return prefix;
	}
}
